import React, { FunctionComponent, useEffect, useState, useRef } from 'react';
import styles from './index.less';
import { HttpService } from '@/core';
import api from '@/api';
import { Tag, Stepper, Icon, Popup } from 'react-vant';
import BScroll from 'better-scroll';
import FoodCard from '../foodcard';
import Shoppingcar from '../shoppingcar';
import { useSelector, useDispatch } from 'umi';
import { IGlobalState } from '@/models/global';

export enum EType {
    /** 特价 */
    te = 2,
    /** 折扣 */
    ze = 1,
}


export interface ISkuProps {
    /** sku属性id */
    skuId: string;
    /** sku属性 */
    title: string;
    /** sku属性值列表 */
    values: Array<{ label: string; value: string }>;
}

export interface ISkuMapProps {
    ids: string;
    price: number;
}

export interface IFoodProps {
    /** id */
    foodId: string;
    /** 描述 */
    description: string;
    /** 图标 */
    icon: string;
    /** 图片 */
    image: string;
    /** 介绍 */
    info: string;
    /** 名称 */
    name: string;
    /** 原价 */
    oldPrice: number | string;
    /** 价格 */
    price: number;
    /** 好评率 */
    rating: number;
    /** 乐售 */
    sellCount: number;
    /** 购买数量 */
    buyNumber: number;
    /** sku信息 */
    sku?: Array<ISkuProps>;
    /** skuMap信息 */
    skuMap?: Array<ISkuMapProps>
}

export interface IGoodsProps {
    name: string;
    type: number;
    foods: Array<IFoodProps>;
    active?: boolean;
}

export interface IProps {
    shadowDisplayChange?: (type: boolean) => void;
}

let haveFinishHttp: boolean = false;

const Sell: FunctionComponent<IProps> = ({ shadowDisplayChange }) => {


    const globalState = useSelector((state: { globalState: IGlobalState }) => state.globalState);
    const dispatch = useDispatch()

    const [goods, setGoods] = useState<Array<IGoodsProps>>([]);

    const sellRef = useRef<HTMLDivElement>(null);

    /** 左侧菜单BS */
    const [leftMenuBs, setLeftMenuBs] = useState<any>({});

    // 购物车pop层展示变量
    const [showPopup, setShowPopup] = useState<boolean>(false);
    // 商品卡片pop层-数量修改展示变量
    const [foodcardPopup, setFoodcardPopup] = useState<boolean>(false);


    // 当前选中的商品
    const [currFood, setCurrFood] = useState<IFoodProps | null>(null);

    useEffect(() => {
        getGoodsList();
    }, []);
    useEffect(() => {
        /** 如果初始化了请求数据才设置Bs对象 */
        if (goods.length && !haveFinishHttp) {
            haveFinishHttp = true;
            const leftBs = new BScroll('.leftMenu', {
                probeType: 3,
                scrollY: true,
                mouseWheel: true,
                useTransition: false,
                click: true,
            });
            setLeftMenuBs(leftBs);
        }
    }, [goods]);

    /** 创建skumap实例 */
    const createSkuMap = (basePrice: number): ISkuMapProps[] => {
        // sku金额信息匹配
        const skuMap: Array<ISkuMapProps> = [
            { ids: '0-1,1-0,2-0', price: basePrice + 1 },
            { ids: '0-1,1-0,2-1', price: basePrice + 1 },
            { ids: '0-1,1-0,2-2', price: basePrice + 1 },
            { ids: '0-1,1-1,2-0', price: basePrice + 1 },
            { ids: '0-1,1-1,2-1', price: basePrice + 1 },
            { ids: '0-1,1-1,2-2', price: basePrice + 1 },
            { ids: '0-1,1-2,2-0', price: basePrice + 1 },
            { ids: '0-1,1-2,2-1', price: basePrice + 1 },
            { ids: '0-1,1-2,2-2', price: basePrice + 1 },
            { ids: '0-1,1-3,2-0', price: basePrice + 1 },
            { ids: '0-1,1-3,2-1', price: basePrice + 1 },
            { ids: '0-1,1-3,2-2', price: basePrice + 1 },
            { ids: '0-2,1-0,2-0', price: basePrice + 2 },
            { ids: '0-2,1-0,2-1', price: basePrice + 2 },
            { ids: '0-2,1-0,2-2', price: basePrice + 2 },
            { ids: '0-2,1-1,2-0', price: basePrice + 2 },
            { ids: '0-2,1-1,2-1', price: basePrice + 2 },
            { ids: '0-2,1-1,2-2', price: basePrice + 2 },
            { ids: '0-2,1-2,2-0', price: basePrice + 2 },
            { ids: '0-2,1-2,2-1', price: basePrice + 2 },
            { ids: '0-2,1-2,2-2', price: basePrice + 2 },
            { ids: '0-2,1-3,2-0', price: basePrice + 2 },
            { ids: '0-2,1-3,2-1', price: basePrice + 2 },
            { ids: '0-2,1-3,2-2', price: basePrice + 2 }
        ]
        return skuMap
    }

    /** 获取商品列表 */
    const getGoodsList = () => {
        // sku列表
        const sku: ISkuProps[] = [
            { skuId: '0', title: '规格', values: [{ label: '小碗', value: '0-0' }, { label: '中碗', value: '0-1' }, { label: '大碗', value: '0-2' }] },
            { skuId: '1', title: '甜度', values: [{ label: '全糖', value: '1-0' }, { label: '半糖', value: '1-1' }, { label: '无糖', value: '1-2' }, { label: '三分糖', value: '1-3' }] },
            { skuId: '2', title: '温度', values: [{ label: '热', value: '2-0' }, { label: '常温', value: '2-1' }, { label: '冷', value: '2-2' }] }
        ]
        HttpService.get(api.goodsList, {}).then((res: any) => {
            let { errno, data } = res as { errno: number; data: IGoodsProps[]; };
            /** 可以再缓存里加上当前用户的购物车信息，同步一下 */
            if (data && errno === 0) {
                data = data.map((item, index) => ({
                    ...item,
                    foods: item.foods.map((fooditem, num) => ({
                        ...fooditem,
                        foodId: 'food' + index + '-' + num,
                        buyNumber: 0,
                        sku: index === 1 ? undefined : sku,
                        skuMap: index === 1 ? undefined : createSkuMap(fooditem.price)
                    }))
                }))
                console.log('data >>> ', data)
                setGoods(
                    data.map((item: IGoodsProps, index: number) => ({
                        ...item,
                        active: index === 0 ? true : false,
                    })),
                );
            }
        });
    };

    /** 展开或者隐藏购物车popup层 */
    const changeCartPopupVis = (type: boolean) => {
        setShowPopup(type);
        shadowDisplayChange?.(type);
    }

    /** 选择左侧bs某一项 */
    const checkLeftBsItem = (index: number | string) => {
        index =
            typeof index === 'string'
                ? goods.findIndex((item) => item.name === index)
                : index;
        if (index >= 0) {
            leftMenuBs.scrollToElement('.goods' + index, 300, false, true);
            document
                .querySelector('.foods' + index)
                ?.scrollIntoView({ behavior: 'smooth' });
            setGoods(
                goods.map((item, num) => ({
                    ...item,
                    active: index === num ? true : false,
                })),
            );
        }
    };


    /** 获取某一分类下选中的所有商品数量 */
    const getTotalNums = (foods: IFoodProps[]) => {
        let total = 0;
        foods.forEach(item => total += item.buyNumber);
        return total
    }

    /** 添加商品到购物车 */
    const addFoodToCart = (item: IFoodProps) => {
        setCurrFood(item);
        setFoodcardPopup(true)
    }
    /** 减少购物车的商品 */
    const reduceFoodByCart = (item: IFoodProps) => {
        setShowPopup(true)
    }


    const getIndex = (_goods: IGoodsProps[], id: string) => {
        let firstIndex = 0, lastIndex = 0;
        _goods.forEach((item, i) => {
            item.foods.forEach((itemize, j) => {
                if (itemize.foodId === id) {
                    firstIndex = i;
                    lastIndex = j;
                }
            })
        })
        return {
            firstIndex,
            lastIndex
        }
    }

    /** dva数据同步到goods */
    const syncGoodsByDva = () => {
        const { shoppingcars } = globalState;
        const _goods = [...goods].map(item => {
            item.foods = item.foods.map(itemize => ({ ...itemize, buyNumber: 0, buy_numbers: 0 }))
            return item
        });
        if (shoppingcars.length) {
            shoppingcars.forEach(item => {
                const { firstIndex, lastIndex } = getIndex(_goods, item.foodId);
                _goods[firstIndex].foods[lastIndex].buyNumber += item.buy_numbers;
            })
        }
        setGoods(_goods)
    }


    /** 获取dva里购物车里商品总额 */
    const getDvaShoppingcarTotalPrice = () => {
        const { shoppingcars } = globalState;
        let totalPrice = 0;
        shoppingcars.forEach(food => {
            const { price, skuSpliceId, skuMap, buy_numbers } = food;
            let skuPrice = price * buy_numbers;
            if (skuSpliceId.includes('|')) {
                const skuIds = skuSpliceId.split('|')[1];
                skuMap?.forEach(item => {
                    if (item.ids === skuIds) skuPrice = (item.price * buy_numbers)
                })
            }
            totalPrice += skuPrice
        })
        return totalPrice
    }

    /** 获取dva里商品总数 */
    const getDvaFoodsCount = () => {
        let { shoppingcars } = globalState, totalNums = 0;
        shoppingcars.forEach(item => {
            totalNums += item.buy_numbers
        })
        return totalNums
    }

    return (
        <div className={styles.sell} ref={sellRef}>
            <div className={styles.sell_top}>
                <div className={`${styles.sell_top_scrleft} leftMenu`}>
                    <ul className={styles.sell_top_scrleft_ul}>
                        {goods?.map((item: IGoodsProps, index: number) => (
                            <li
                                onClick={() => checkLeftBsItem(index)}
                                key={'goods' + index}
                                className={`goods${index} ${styles.sell_top_scrleft_ul_li} ${item.active ? styles.sell_top_scrleft_ul_li_active : ''
                                    }`}
                            >
                                <div className={styles.sell_top_scrleft_ul_li_text}>
                                    {item.type === EType.te ? (
                                        <Tag color="#4fc08d" textColor="#ffffff">
                                            特
                                        </Tag>
                                    ) : null}
                                    {item.type === EType.ze ? (
                                        <Tag color="#1897ff" textColor="#ffffff">
                                            折
                                        </Tag>
                                    ) : null}
                                    {item.name}
                                    {
                                        getTotalNums(item.foods) ? (<div className={styles.num}>{getTotalNums(item.foods)}</div>) : null
                                    }
                                </div>
                            </li>
                        ))}
                    </ul>
                </div>
                <div className={styles.sell_top_scrright}>
                    <ul className={styles.sell_top_scrright_ul}>
                        {goods?.map((item: IGoodsProps, index: number) => (
                            <li
                                key={'goodsitem' + index}
                                className={`${styles.sell_top_scrright_ul_li} foods${index}`}
                            >
                                <p>{item.name}</p>
                                {item.foods?.map((food: IFoodProps, num: number) => (
                                    <div
                                        key={'goodsfooditem' + num}
                                        className={styles.sell_top_scrright_ul_li_food}
                                    >
                                        <img src={food.image} alt="" />
                                        <div className={styles.sell_top_scrright_ul_li_food_info}>
                                            <div className={styles.name}>{food.name}</div>
                                            {food.description && (
                                                <div className={styles.desc}>{food.description}</div>
                                            )}
                                            <div className={styles.desc}>
                                                <span>月售{food.sellCount}份</span>
                                                <span>好评率{food.rating}%</span>
                                            </div>
                                            <div className={styles.buy}>
                                                <span className={styles.buy_price}>
                                                    ￥ {food.price}
                                                </span>
                                                {
                                                    food.buyNumber ?
                                                        <Stepper
                                                            value={food.buyNumber}
                                                            min={0}
                                                            theme="round"
                                                            buttonSize="22"
                                                            disableInput
                                                            beforeChange={() => false}
                                                            onPlus={() => { addFoodToCart(food); }}
                                                            onMinus={() => reduceFoodByCart(food)}
                                                        /> : <div onClick={() => { addFoodToCart(food) }} aria-label="add" className={`rv-stepper__plus ${styles.buy_button}`}></div>
                                                }
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </li>
                        ))}
                    </ul>
                </div>
            </div>
            <div className={styles.sell_down}>
                <div
                    className={`${styles.sell_down_left} ${globalState.shoppingcars.length ? styles.sell_down_left_active : ''}`}
                    onClick={() => {
                        if (globalState.shoppingcars.length) {
                            changeCartPopupVis(!showPopup)
                        }
                    }}
                >
                    <div className={styles.sell_down_left_icon}>
                        <div className={styles.sell_down_left_icon_inner}>
                            <Icon name="shopping-cart-o" />
                            {
                                getDvaFoodsCount() ?
                                    <div className={styles.sell_down_left_icon_inner_foodnum}>{getDvaFoodsCount()}</div>
                                    : null
                            }
                        </div>
                    </div>
                    <div className={styles.sell_down_left_price}>￥{getDvaShoppingcarTotalPrice()}</div>
                    <div className={styles.sell_down_left_postfree}>另需配送费￥{globalState.basePostFree}元</div>
                </div>
                <div className={`${styles.sell_down_right} ${getDvaShoppingcarTotalPrice() >= globalState.minPrice&&globalState.minPrice!==0 ? styles.sell_down_right_active : ''}`} onClick={() => console.log(globalState)}>
                    {
                        (() => {
                            const totalPrice = getDvaShoppingcarTotalPrice()
                            let text = `￥${globalState.minPrice}元起送`;
                            if (totalPrice > 0) {
                                text = totalPrice >= globalState.minPrice ? '去结算' : `差￥${globalState.minPrice - totalPrice}起送`
                            }
                            return (
                                <span>{text}</span>
                            )
                        })()
                    }
                </div>
            </div>
            <Popup
                position="bottom"
                className='cart-pop'
                visible={showPopup}
                teleport={() => sellRef.current as HTMLElement}
                onOpen={() => changeCartPopupVis(true)}
                onClose={() => changeCartPopupVis(false)}
            >
                <Shoppingcar syncGoodsByDva={syncGoodsByDva} changeCartPopupVis={changeCartPopupVis} ></Shoppingcar>
            </Popup>
            <Popup
                className='foodcard-pop'
                destroyOnClose
                visible={foodcardPopup}
                onClickOverlay={() => { setFoodcardPopup(false); setCurrFood(null) }}
                style={{ borderRadius: '5px' }}
            >
                <FoodCard
                    foodDetail={currFood}
                    hideCartPop={() => { setFoodcardPopup(false); setCurrFood(null); }}
                    syncGoodsByDva={syncGoodsByDva}
                ></FoodCard>
            </Popup>
        </div>
    );
};

export default Sell;
